const http = require('http');
const mysql = require('mysql');
const timetrack = require('./timetrack');

const db = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'QWEqwe#21',
  database: 'timetrack'
});

const server = http.createServer(function (req, res) {
  switch (req.method) {
    case 'POST':
      switch (req.url) {
        case '/':
          timetrack.add(db, req, res);
          break;

        case '/archive':
          timetrack.archive(db, req, res);
          break;

        case '/delete':
          timetrack.delete(db, req, res);
          break;
      }
      break;

    case 'GET':
      switch (req.url) {
        case '/':
          timetrack.show(db, res);
          break;

        case '/archived':
          timetrack.showArchived(db, res);
          break;
      }
      break;
  }
});

db.query(
  `
CREATE TABLE IF NOT EXISTS work (
  id INT(10) NOT NULL AUTO_INCREMENT,
  hours DECIMAL(5, 2) DEFAULT 0,
  date DATE,
  archived INT(1) DEFAULT 0,
  description LONGTEXT,
  PRIMARY KEY(id)
  )
`,
  function (err) {
    if (err) throw err;
    console.log('Server started...');
    server.listen(3000, 'localhost');
  }
);
